package com.yoouce.patchmng.util;

import com.ice.tar.TarEntry;
import com.ice.tar.TarInputStream;

import java.io.*;

/**
 * java 解压缩tar包
 * Created by Scott.Lee on 15-10-13.
 */
public class TarUtil {

    public static void inflat(String tarPath, String targetPath) {
        InputStream inputstream = null;
        OutputStream outputstream = null;
        TarInputStream zis = null;
        try {
            File file = new File(tarPath);
            File tempFile = null;
            inputstream = new FileInputStream(file);
            zis = new TarInputStream(inputstream);
            //关键在于这个TarEntry 的理解，实际你的tar包里有多少文件就有多少TarEntry
            TarEntry tarEntry = null;
            while ((tarEntry = zis.getNextEntry()) != null) {
                tempFile = new File(targetPath + tarEntry.getName());
                tempFile.createNewFile();
                outputstream = new FileOutputStream(tempFile);
                //定一个缓存池 可以根据实际情况调整大小（事实证 明很有用）
                byte[] buffer = new byte[1024 * 50];
                while (true) {
                    int readsize = zis.read(buffer);
                    outputstream.write(buffer);
                    if (readsize < 1024 * 50) {
                        break;
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputstream.flush();
                inputstream.close();
                zis.close();
                outputstream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {
        TarUtil.inflat("/home/administrator/IdeaProjects/patchmng/target/patchmng/upload/patch/lcs-20151013104152/patch_20151006.tar.gz",
                "/home/administrator/IdeaProjects/patchmng/target/patchmng/upload/patch/lcs-20151013104152/");
    }

}
